package com.smartwork.common.mobile.wechat.thread;


import com.smartwork.common.mobile.wechat.bean.AccessToken;
import com.smartwork.common.mobile.wechat.util.WeixinConfUtils;
import com.smartwork.common.mobile.wechat.util.WeixinUtil;
import com.smartwork.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;

/** 
 * 定时获取微信access_token的线程 
 *  
 * @author liuyq 
 * @date 2013-05-02 
 */  
public class TokenThread implements Runnable {  
    private static Logger log = LoggerFactory.getLogger(TokenThread.class);
    
    private static AccessToken accessToken = null;

    private static ConcurrentHashMap<String, AccessToken> accessTokenConcurrentHashMap
                                                     = new ConcurrentHashMap<String, AccessToken>();

    private String groupId;

    public TokenThread(String groupId) {
        this.groupId = groupId;
    }

    public void run() {
        while (true) {  
            try {  
            	accessToken = WeixinUtil.getAccessToken(groupId);
                if (null != accessToken) {
                    accessTokenConcurrentHashMap.put(groupId, accessToken);
                    WeixinConfUtils.setValue(groupId,"accessToken", accessToken.getToken());
                    // 休眠7000秒  
                    Thread.sleep((accessToken.getExpiresIn() - 200) * 1000);  
                } else {  
                    // 如果access_token为null，60秒后再获取  
                    Thread.sleep(60 * 1000);
                }  
            } catch (InterruptedException e) {  
                try {  
                    Thread.sleep(60 * 1000);  
                } catch (InterruptedException e1) {  
                    log.error("{}", e1);  
                }  
                log.error("{}", e);  
            }
        }  
    }  
    
    public static synchronized String getAccessTokenStr(String groupId) {
        log.debug("getTokenBy:{}",groupId);
    	if(accessTokenConcurrentHashMap == null || accessTokenConcurrentHashMap.size() == 0) {
    		String token = WeixinConfUtils.getValue(groupId, "accessToken");
            if (StringUtils.isEmpty(token)) {
                return null;
            } else {
                return token;
            }
    	}
    	return accessTokenConcurrentHashMap.get(groupId).getToken();
    }
}